package zsy.test.java.util.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangshuaiyin
 * @date 2022/4/2 11:39
 */
@Slf4j
public class LockDemo {
    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 对业务逻辑加锁，避免多线程频繁调用导致的IO消耗
     * <p>
     * 如果已经有请求在处理该逻辑，执行过程中的请求在等待100ms后会放弃执行
     */
    public void doBusiness() {
        try {
            if (LOCK.tryLock(100, TimeUnit.MILLISECONDS)) {
                log.info("LockDemo --> 业务逻辑执行，当前请求处理");
                try {
                    // 执行业务逻辑
                } finally {
                    LOCK.unlock();
                }
            } else {
                log.info("LockDemo --> 业务逻辑执行[其他请求线程正在处理]");
            }
        } catch (InterruptedException ignore) {
        }
    }
}
